import React, { useMemo, useState } from "react";
import {
  Button,
  Card,
  DatePicker,
  Form,
  Input,
  Select,
  Space,
  Table,
  Tag,
  Modal,
  InputNumber,
  Popconfirm,
  message,
} from "antd";
import dayjs from "dayjs";

type InboundRecord = {
  key: React.Key;
  index: number;
  orderNo: string;
  type: string;
  status: "草稿" | "待审核" | "已完成";
  date: string;
  warehouse: string;
  relatedNo: string;
  goods: string;
  handler: string;
  qty: number;
  amount: number;
  creator: string;
  department: string;
  makeTime: string;
  reviewer: string;
  reviewTime: string;
};

// 列在 Table 中内联构造，移除旧常量避免未使用告警

const mockData: InboundRecord[] = Array.from({ length: 60 }).map((_, i) => ({
  key: i + 1,
  index: i + 1,
  orderNo: `RKDH${(1800 + i).toString().padStart(4, "0")}`,
  type: ["采购入库", "生产入库", "销售退货", "期初入库"][i % 4],
  status: (["草稿", "待审核", "已完成"] as InboundRecord["status"][])[i % 3],
  date: "2024-02-29",
  warehouse: "货品仓库",
  relatedNo: "JHDH058886",
  goods: "三锅头、可乐、奶茶、啤酒、白酒、果汁儿",
  handler: "赵依依",
  qty: 50,
  amount: 500.0,
  creator: "甄惜梦",
  department: "采购部",
  makeTime: "2024-02-29 21:35:55",
  reviewer: "赵子墨",
  reviewTime: "2024-02-29 21:35:55",
}));
const initialData = mockData;

export default function GoStorage() {
  const [form] = Form.useForm();
  const [dataSource, setDataSource] = useState<InboundRecord[]>(initialData);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [addOpen, setAddOpen] = useState(false);
  const [adding, setAdding] = useState(false);
  const [addForm] = Form.useForm<Partial<InboundRecord>>();
  const [editOpen, setEditOpen] = useState(false);
  const [editingKey, setEditingKey] = useState<React.Key | null>(null);
  const [editForm] = Form.useForm<Partial<InboundRecord>>();

  const handleSearch = () => {
    const values = form.getFieldsValue();
    const { orderNo, type, status, date, warehouse } = values;
    const filtered = initialData.filter((item) => {
      const byOrder = orderNo ? item.orderNo.includes(orderNo) : true;
      const byType = type ? item.type === type : true;
      const byStatus = status ? item.status === status : true;
      const byDate = date
        ? item.date === dayjs(date).format("YYYY-MM-DD")
        : true;
      const byWh = warehouse ? item.warehouse === warehouse : true;
      return byOrder && byType && byStatus && byDate && byWh;
    });
    setDataSource(filtered);
  };

  const handleReset = () => {
    form.resetFields();
    setDataSource(initialData);
  };

  const disabledBySelection = useMemo(
    () => selectedRowKeys.length === 0,
    [selectedRowKeys]
  );

  const openAdd = () => {
    addForm.resetFields();
    addForm.setFieldsValue({
      type: "采购入库",
      date: dayjs(),
      warehouse: "货品仓库",
      qty: 1,
      amount: 0,
      status: "草稿",
    } as any);
    setAddOpen(true);
  };

  const submitAdd = async () => {
    try {
      const values = await addForm.validateFields();
      setAdding(true);
      const nextIndex = dataSource.length + 1;
      const newRecord: InboundRecord = {
        key: Date.now(),
        index: nextIndex,
        orderNo: `RKDH${(3000 + nextIndex).toString().padStart(4, "0")}`,
        type: values.type!,
        status: values.status as InboundRecord["status"],
        date: dayjs(values.date).format("YYYY-MM-DD"),
        warehouse: values.warehouse!,
        relatedNo: values.relatedNo || "—",
        goods: values.goods || "—",
        handler: values.handler || "—",
        qty: Number(values.qty || 0),
        amount: Number(values.amount || 0),
        creator: values.creator || "—",
        department: values.department || "—",
        makeTime: dayjs().format("YYYY-MM-DD HH:mm:ss"),
        reviewer: values.reviewer || "—",
        reviewTime: values.reviewTime
          ? dayjs(values.reviewTime).format("YYYY-MM-DD HH:mm:ss")
          : "—",
      };
      setDataSource((prev) => [
        newRecord,
        ...prev.map((p, i) => ({ ...p, index: i + 2 })),
      ]);
      setAddOpen(false);
      message.success("新增成功");
    } finally {
      setAdding(false);
    }
  };

  const handleDelete = () => {
    setDataSource((prev) =>
      prev
        .filter((r) => !selectedRowKeys.includes(r.key))
        .map((r, i) => ({ ...r, index: i + 1 }))
    );
    setSelectedRowKeys([]);
    message.success("删除成功");
  };

  const handleCopy = () => {
    setDataSource((prev) => {
      const copies = prev
        .filter((r) => selectedRowKeys.includes(r.key))
        .map((r) => ({
          ...r,
          key: `${r.key}-c-${Date.now()}`,
          orderNo: `${r.orderNo}-C`,
          status: "草稿" as const,
        }));
      const next = [...copies, ...prev];
      return next.map((r, i) => ({ ...r, index: i + 1 }));
    });
    message.success("复制成功");
  };

  const handleAudit = () => {
    setDataSource((prev) =>
      prev.map((r) =>
        selectedRowKeys.includes(r.key) ? { ...r, status: "已完成" } : r
      )
    );
    message.success("审核完成");
  };

  const handleRevoke = () => {
    setDataSource((prev) =>
      prev.map((r) =>
        selectedRowKeys.includes(r.key) ? { ...r, status: "草稿" } : r
      )
    );
    message.success("已撤销为草稿");
  };

  const handleExport = () => {
    const headers = [
      "序号",
      "入库单号",
      "入库类型",
      "状态",
      "入库日期",
      "仓库名称",
      "关联单号",
      "入库货品",
      "经办人",
      "入库数量",
      "入库金额",
      "制单人",
      "所在部门",
      "制单时间",
      "审核人",
      "审核时间",
    ];
    const rows = dataSource.map((r) => [
      r.index,
      r.orderNo,
      r.type,
      r.status,
      r.date,
      r.warehouse,
      r.relatedNo,
      r.goods,
      r.handler,
      r.qty,
      r.amount,
      r.creator,
      r.department,
      r.makeTime,
      r.reviewer,
      r.reviewTime,
    ]);
    const csv = [
      headers.join(","),
      ...rows.map((row) =>
        row.map((v) => `"${String(v ?? "").replace(/"/g, '""')}"`).join(",")
      ),
    ].join("\n");
    const blob = new Blob(["\ufeff" + csv], {
      type: "text/csv;charset=utf-8;",
    });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = `入库管理_${dayjs().format("YYYYMMDD_HHmmss")}.csv`;
    a.click();
    URL.revokeObjectURL(url);
  };

  const handleRefresh = () => {
    setDataSource(initialData);
    setSelectedRowKeys([]);
    message.success("已刷新");
  };

  const handleRowDelete = (key: React.Key) => {
    setDataSource((prev) =>
      prev.filter((r) => r.key !== key).map((r, i) => ({ ...r, index: i + 1 }))
    );
    message.success("已删除");
  };

  const openEdit = (record: InboundRecord) => {
    setEditingKey(record.key);
    editForm.setFieldsValue({
      ...record,
      date: dayjs(record.date),
      reviewTime:
        record.reviewTime && record.reviewTime !== "—"
          ? dayjs(record.reviewTime)
          : undefined,
    } as any);
    setEditOpen(true);
  };

  const submitEdit = async () => {
    const values = await editForm.validateFields();
    const updated: Partial<InboundRecord> = {
      ...values,
      date: values.date
        ? dayjs(values.date as any).format("YYYY-MM-DD")
        : undefined,
      reviewTime: values.reviewTime
        ? dayjs(values.reviewTime as any).format("YYYY-MM-DD HH:mm:ss")
        : undefined,
    };
    setDataSource((prev) =>
      prev.map((r) =>
        r.key === editingKey ? ({ ...r, ...updated } as InboundRecord) : r
      )
    );
    setEditOpen(false);
    setEditingKey(null);
    message.success("已保存");
  };

  return (
    <Space direction="vertical" size={12} style={{ width: "100%" }}>
      <Card bordered={false} bodyStyle={{ paddingBottom: 0 }}>
        <Form form={form} layout="inline" onFinish={handleSearch}>
          <Form.Item label="入库单号" name="orderNo">
            <Input placeholder="请输入" allowClear style={{ width: 200 }} />
          </Form.Item>
          <Form.Item label="入库类型" name="type">
            <Select
              placeholder="请选择"
              allowClear
              options={[
                { label: "采购入库", value: "采购入库" },
                { label: "生产入库", value: "生产入库" },
                { label: "销售退货", value: "销售退货" },
                { label: "期初入库", value: "期初入库" },
              ]}
              style={{ width: 160 }}
            />
          </Form.Item>
          <Form.Item label="单据状态" name="status">
            <Select
              placeholder="请选择"
              allowClear
              options={[
                { label: "草稿", value: "草稿" },
                { label: "待审核", value: "待审核" },
                { label: "已完成", value: "已完成" },
              ]}
              style={{ width: 140 }}
            />
          </Form.Item>
          <Form.Item label="入库日期" name="date">
            <DatePicker style={{ width: 160 }} />
          </Form.Item>
          <Form.Item label="仓库名称" name="warehouse">
            <Select
              placeholder="请选择"
              allowClear
              options={[
                { label: "货品仓库", value: "货品仓库" },
                { label: "原料仓库", value: "原料仓库" },
              ]}
              style={{ width: 160 }}
            />
          </Form.Item>

          <Space style={{ marginLeft: "auto", marginBottom: 16 }}>
            <Button onClick={handleReset}>重置</Button>
            <Button type="primary" htmlType="submit">
              查询
            </Button>
          </Space>
        </Form>
      </Card>

      <Card bordered={false} bodyStyle={{ paddingTop: 12 }}>
        <Space style={{ marginBottom: 12 }} wrap>
          <Button type="primary" onClick={openAdd}>
            新增
          </Button>
          <Popconfirm
            title="确定删除选中记录吗？"
            onConfirm={handleDelete}
            disabled={disabledBySelection}>
            <Button danger disabled={disabledBySelection}>
              删除
            </Button>
          </Popconfirm>
          <Button disabled={disabledBySelection} onClick={handleCopy}>
            复制
          </Button>
          <Button disabled={disabledBySelection} onClick={handleAudit}>
            审核
          </Button>
          <Button disabled={disabledBySelection} onClick={handleRevoke}>
            撤销
          </Button>
          <Button onClick={handleExport}>导出</Button>
          <Button onClick={handleRefresh}>刷新</Button>
        </Space>

        <Table
          rowSelection={{ selectedRowKeys, onChange: setSelectedRowKeys }}
          columns={(function () {
            const cols = [
              {
                title: "序号",
                dataIndex: "index",
                width: 70,
                fixed: "left" as const,
              },
              {
                title: "入库单号",
                dataIndex: "orderNo",
                width: 140,
                fixed: "left" as const,
              },
              {
                title: "入库类型",
                dataIndex: "type",
                width: 110,
                fixed: "left" as const,
              },
              {
                title: "状态",
                dataIndex: "status",
                width: 100,
                fixed: "left" as const,
                render: (text: InboundRecord["status"]) => {
                  const colorMap: Record<InboundRecord["status"], string> = {
                    草稿: "default",
                    待审核: "orange",
                    已完成: "green",
                  };
                  return <Tag color={colorMap[text]}>{text}</Tag>;
                },
              },
              {
                title: "入库日期",
                dataIndex: "date",
                width: 120,
                fixed: "left" as const,
              },
              { title: "仓库名称", dataIndex: "warehouse", width: 120 },
              { title: "关联单号", dataIndex: "relatedNo", width: 140 },
              { title: "入库货品", dataIndex: "goods", ellipsis: true },
              { title: "经办人", dataIndex: "handler", width: 100 },
              { title: "入库数量", dataIndex: "qty", width: 100 },
              { title: "入库金额", dataIndex: "amount", width: 110 },
              { title: "制单人", dataIndex: "creator", width: 100 },
              { title: "所在部门", dataIndex: "department", width: 120 },
              { title: "制单时间", dataIndex: "makeTime", width: 180 },
              { title: "审核人", dataIndex: "reviewer", width: 100 },
              { title: "审核时间", dataIndex: "reviewTime", width: 180 },
              {
                title: "操作",
                key: "action",
                fixed: "right" as const,
                width: 160,
                render: (_: any, record: InboundRecord) => (
                  <Space>
                    <Button
                      type="link"
                      size="small"
                      onClick={() => openEdit(record)}>
                      编辑
                    </Button>
                    <Popconfirm
                      title="确认删除该行？"
                      onConfirm={() => handleRowDelete(record.key)}>
                      <Button type="link" size="small">
                        删除
                      </Button>
                    </Popconfirm>
                  </Space>
                ),
              },
            ];
            return cols as any;
          })()}
          dataSource={dataSource}
          bordered
          size="middle"
          pagination={{
            pageSize: 5,
            showQuickJumper: true,
            showSizeChanger: true,
            pageSizeOptions: [5, 10, 20, 50],
            showTotal: (total) => `共 ${total} 条`,
          }}
          scroll={{ x: 1800 }}
        />
      </Card>

      <Modal
        title="编辑入库单"
        open={editOpen}
        onCancel={() => setEditOpen(false)}
        onOk={submitEdit}
        okText="保存"
        cancelText="取消"
        destroyOnClose>
        <Form
          form={editForm}
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 16 }}
          preserve={false}>
          <Form.Item
            label="入库类型"
            name="type"
            rules={[{ required: true, message: "请选择入库类型" }]}>
            <Select
              options={[
                { label: "采购入库", value: "采购入库" },
                { label: "生产入库", value: "生产入库" },
                { label: "销售退货", value: "销售退货" },
                { label: "期初入库", value: "期初入库" },
              ]}
            />
          </Form.Item>
          <Form.Item
            label="入库日期"
            name="date"
            rules={[{ required: true, message: "请选择日期" }]}>
            <DatePicker style={{ width: "100%" }} />
          </Form.Item>
          <Form.Item
            label="仓库名称"
            name="warehouse"
            rules={[{ required: true, message: "请选择仓库" }]}>
            <Select
              options={[
                { label: "货品仓库", value: "货品仓库" },
                { label: "原料仓库", value: "原料仓库" },
              ]}
            />
          </Form.Item>
          <Form.Item label="关联单号" name="relatedNo">
            <Input placeholder="可选" />
          </Form.Item>
          <Form.Item label="入库货品" name="goods">
            <Input />
          </Form.Item>
          <Form.Item label="经办人" name="handler">
            <Input />
          </Form.Item>
          <Form.Item
            label="入库数量"
            name="qty"
            rules={[{ required: true, message: "请输入数量" }]}>
            <InputNumber min={0} style={{ width: "100%" }} />
          </Form.Item>
          <Form.Item
            label="入库金额"
            name="amount"
            rules={[{ required: true, message: "请输入金额" }]}>
            <InputNumber min={0} style={{ width: "100%" }} />
          </Form.Item>
          <Form.Item label="制单人" name="creator">
            <Input />
          </Form.Item>
          <Form.Item label="所在部门" name="department">
            <Input />
          </Form.Item>
          <Form.Item
            label="单据状态"
            name="status"
            rules={[{ required: true, message: "请选择状态" }]}>
            <Select
              options={[
                { label: "草稿", value: "草稿" },
                { label: "待审核", value: "待审核" },
                { label: "已完成", value: "已完成" },
              ]}
            />
          </Form.Item>
          <Form.Item label="审核人" name="reviewer">
            <Input />
          </Form.Item>
          <Form.Item label="审核时间" name="reviewTime">
            <DatePicker showTime style={{ width: "100%" }} />
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title="新增入库单"
        open={addOpen}
        confirmLoading={adding}
        onCancel={() => setAddOpen(false)}
        onOk={submitAdd}
        okText="保存"
        cancelText="取消"
        destroyOnClose>
        <Form
          form={addForm}
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 16 }}
          preserve={false}>
          <Form.Item
            label="入库类型"
            name="type"
            rules={[{ required: true, message: "请选择入库类型" }]}>
            <Select
              options={[
                { label: "采购入库", value: "采购入库" },
                { label: "生产入库", value: "生产入库" },
                { label: "销售退货", value: "销售退货" },
                { label: "期初入库", value: "期初入库" },
              ]}
            />
          </Form.Item>
          <Form.Item
            label="入库日期"
            name="date"
            rules={[{ required: true, message: "请选择日期" }]}>
            <DatePicker style={{ width: "100%" }} />
          </Form.Item>
          <Form.Item
            label="仓库名称"
            name="warehouse"
            rules={[{ required: true, message: "请选择仓库" }]}>
            <Select
              options={[
                { label: "货品仓库", value: "货品仓库" },
                { label: "原料仓库", value: "原料仓库" },
              ]}
            />
          </Form.Item>
          <Form.Item label="关联单号" name="relatedNo">
            <Input placeholder="可选" />
          </Form.Item>
          <Form.Item label="入库货品" name="goods">
            <Input placeholder="如：啤酒、白酒…" />
          </Form.Item>
          <Form.Item label="经办人" name="handler">
            <Input />
          </Form.Item>
          <Form.Item
            label="入库数量"
            name="qty"
            rules={[{ required: true, message: "请输入数量" }]}>
            <InputNumber min={0} style={{ width: "100%" }} />
          </Form.Item>
          <Form.Item
            label="入库金额"
            name="amount"
            rules={[{ required: true, message: "请输入金额" }]}>
            <InputNumber min={0} style={{ width: "100%" }} />
          </Form.Item>
          <Form.Item label="制单人" name="creator">
            <Input />
          </Form.Item>
          <Form.Item label="所在部门" name="department">
            <Input />
          </Form.Item>
          <Form.Item
            label="单据状态"
            name="status"
            rules={[{ required: true, message: "请选择状态" }]}>
            <Select
              options={[
                { label: "草稿", value: "草稿" },
                { label: "待审核", value: "待审核" },
                { label: "已完成", value: "已完成" },
              ]}
            />
          </Form.Item>
          <Form.Item label="审核人" name="reviewer">
            <Input />
          </Form.Item>
          <Form.Item label="审核时间" name="reviewTime">
            <DatePicker showTime style={{ width: "100%" }} />
          </Form.Item>
        </Form>
      </Modal>
    </Space>
  );
}
